package com.sky.handler;

import cn.hutool.core.collection.CollUtil;
import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 处理SQL异常：重复值
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Duplicate entry '32323' for key '用户名'
        //    0       1      2     3   4     5
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] s = message.split(" ");
            String msgValue = s[2];
            String msgName = s[5];
            String msg = msgName.replace("'","") + ":" + msgValue.replace("'","") + "," + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    /**
     * 处理@Validated参数校验异常
     */
    @ExceptionHandler
    public Result exceptionHandler(MethodArgumentNotValidException ex){
        BindingResult result = ex.getBindingResult();
        StringBuffer stringBuffer = new StringBuffer();
        if(result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            if(CollUtil.isNotEmpty(allErrors)){
                allErrors.forEach(p->{
                    FieldError fieldError = (FieldError) p;
                    log.warn("Bad Request Parameters: dto entity [{}],field [{}],message [{}]",fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage());
                    stringBuffer.append(fieldError.getDefaultMessage());
                });
            }
        }
        return Result.error(stringBuffer.toString());
    }
}
